package com.cn.shuangzi.ad.manager;

import android.app.Activity;
import android.graphics.Point;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.bytedance.msdk.api.AdError;
import com.bytedance.msdk.api.GMAdEcpmInfo;
import com.bytedance.msdk.api.v2.GMAdConstant;
import com.bytedance.msdk.api.v2.GMAdSize;
import com.bytedance.msdk.api.v2.GMMediationAdSdk;
import com.bytedance.msdk.api.v2.GMSettingConfigCallback;
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAd;
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAdListener;
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAdLoadCallback;
import com.bytedance.msdk.api.v2.slot.GMAdSlotBanner;
import com.cn.shuangzi.ad.ADManager;
import com.cn.shuangzi.ad.bean.YlhErrorInfo;
import com.cn.shuangzi.ad.util.ADConst;
import com.cn.shuangzi.ad.util.OnAdClosedListener;
import com.cn.shuangzi.ad.view.AlertVipDialog;
import com.cn.shuangzi.common.SZConst;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZXmlUtil;
import com.qq.e.ads.banner2.UnifiedBannerView;

import java.util.List;

import androidx.annotation.NonNull;

public class AdBannerManager {

    private GMBannerAd mBannerViewAd;
    private Activity mActivity;
    private GMBannerAdLoadCallback mBannerAdLoadCallback;
    private String mAdUnitId; //广告位
    private String scenarioId; //广告位
    private ViewGroup bannerContainer;
    private Class<?> classVip;
    private OnAdClosedListener onAdClosedListener;

    public AdBannerManager(Activity activity, ViewGroup bannerContainer) {
        this(activity, bannerContainer, null,null);
    }

    public AdBannerManager(Activity activity, ViewGroup bannerContainer, Class<?> classVip) {
        this(activity, bannerContainer, classVip,null);
    }

    public AdBannerManager(Activity activity, ViewGroup bannerContainer, Class<?> classVip, OnAdClosedListener onAdClosedListener) {
        //如果接入了Unity sdk 建议提前初始化
//        GMAdManagerHolder.initUnitySdkBanner(activity);
        mActivity = activity;
        this.classVip = classVip;
        this.bannerContainer = bannerContainer;
        this.onAdClosedListener = onAdClosedListener;
        mBannerAdLoadCallback = new GMBannerAdLoadCallback() {
            @Override
            public void onAdFailedToLoad(@NonNull AdError adError) {
                SZUtil.logError("banner加载失败：" + adError);
                if(mAdUnitId!=null) {
                    loadAdWithCallback(mAdUnitId,scenarioId);
                }
            }

            @Override
            public void onAdLoaded() {
                showBannerAd();
            }
        };
    }

    public GMBannerAd getBannerAd() {
        return mBannerViewAd;
    }

    public void loadAdWithCallback(final String adUnitId) {
        loadAdWithCallback(adUnitId,null);
    }
    public void loadAdWithCallback(String adUnitId,String scenarioId) {
        if(adUnitId == null){
            return;
        }
        this.mAdUnitId = adUnitId;
        this.scenarioId = scenarioId;
        /**
         * 判断当前是否存在config 配置 ，如果存在直接加载广告 ，如果不存在则注册config加载回调
         */
        if (GMMediationAdSdk.configLoadSuccess()) {
            SZUtil.logError("load ad 当前config配置存在，直接加载广告");
            loadBannerAd();
        } else {
            ADManager.getInstance().initGMAd();
            SZUtil.logError("load ad 当前config配置不存在，正在请求config配置....");
            GMMediationAdSdk.registerConfigCallback(mSettingConfigCallback); //不用使用内部类，否则在ondestory中无法移除该回调
        }
    }

    private void loadBannerAd() {
        /**
         * 注：每次加载banner的时候需要新建一个GMBannerAd，一个广告对象只能load一次，banner广告对象getBannerView只能一次，第二次调用会返回空
         */
        if (mBannerViewAd != null) {
            mBannerViewAd.destroy();
        }
        mBannerViewAd = new GMBannerAd(mActivity, mAdUnitId);

        //设置广告事件监听
        mBannerViewAd.setAdBannerListener(new GMBannerAdListener() {
            @Override
            public void onAdOpened() {
            }

            @Override
            public void onAdLeftApplication() {
            }

            @Override
            public void onAdClosed() {
                if (classVip != null && !mActivity.isFinishing()) {
                    SZXmlUtil szXmlUtil = new SZXmlUtil(SZConst.SETTING);
                    if(!szXmlUtil.getBoolean("isShownBannerVip")){
                        szXmlUtil.put("isShownBannerVip",true);
                        new AlertVipDialog(mActivity, classVip).show();
                    }
                }
                if (onAdClosedListener != null) {
                    onAdClosedListener.onAdClosed();
                }
            }

            @Override
            public void onAdClicked() {

            }

            @Override
            public void onAdShow() {
                GMAdEcpmInfo gmAdEcpmInfo = mBannerViewAd.getShowEcpm();
                SZUtil.logError("banner显示成功！Ecpm="+gmAdEcpmInfo);
                if(gmAdEcpmInfo!=null) {
                    if(!ADManager.getInstance().isYlhPlatform(gmAdEcpmInfo.getAdNetworkPlatformName())) {
                        UnifiedBannerView unifiedBannerView = ADManager.getInstance().getCurrentUnifiedBannerView();
                        YlhErrorInfo ylhErrorInfo = ADManager.getInstance().getBannerErrorInfo();
                        if (gmAdEcpmInfo != null && unifiedBannerView != null && ylhErrorInfo != null) {
                            int ecpm = ylhErrorInfo.getPrice();
                            try {
                                if (ecpm <= 0) {
                                    ecpm = 2 * ADConst.YUAN;
                                }
                                double preEcpm = Double.parseDouble(gmAdEcpmInfo.getPreEcpm());
                                if(preEcpm>0) {
                                    ecpm = (int) (preEcpm + 0.5 * ADConst.YUAN);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            ylhErrorInfo.setPrice(ecpm);
                            unifiedBannerView.sendLossNotification(ecpm, ylhErrorInfo.getReason(), ylhErrorInfo.getAdnId());
                            SZUtil.logError("上报优量汇Banner竞价失败：ylhErrorInfo" + ylhErrorInfo);
                        }
                    }
                }

                ADManager.getInstance().setCurrentUnifiedBannerView(null);
                ADManager.getInstance().setBannerErrorInfo(null);
//
//                int height = bannerContainer.getChildAt(0).getHeight();
//                int width = bannerContainer.getChildAt(0).getWidth();
//                SZUtil.logError("banner高度：" + height);
//                SZUtil.logError("banner宽度：" + width);
                printShowAdInfo();
                printLoadAdInfo();
            }

            @Override
            public void onAdShowFail(@NonNull AdError adError) {
                SZUtil.logError("banner显示失败:" + adError);
                ADManager.getInstance().setCurrentUnifiedBannerView(null);
                ADManager.getInstance().setBannerErrorInfo(null);
                SZUtil.logError("=====banner重新加载=====");
                loadAdWithCallback(mAdUnitId,scenarioId);
            }
        });
        //设置广告配置
        GMAdSlotBanner slotBanner = new GMAdSlotBanner.Builder()
                .setMuted(true)
                .setVolume(0f)
                .setScenarioId(scenarioId)
                .setDownloadType(GMAdConstant.DOWNLOAD_TYPE_POPUP)
                .setBannerSize(GMAdSize.BANNER_CUSTOME)
                .setImageAdSize(SZUtil.px2dip(640), SZUtil.px2dip(100))// GMAdSize.BANNER_CUSTOME可以调用setImageAdSize设置大小
                .setAllowShowCloseBtn(true)//如果广告本身允许展示关闭按钮，这里设置为true就是展示。注：目前只有mintegral支持。
                .build();
        //请求广告，对请求回调的广告作渲染处理
        mBannerViewAd.loadAd(slotBanner, mBannerAdLoadCallback);
    }

    public void destroy() {
        try {
            if (mBannerViewAd != null) {
                mBannerViewAd.destroy();
            }
            mActivity = null;
            mBannerViewAd = null;
            mBannerAdLoadCallback = null;
            GMMediationAdSdk.unregisterConfigCallback(mSettingConfigCallback); //注销config回调
            SZUtil.logError("Banner destroy成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * config回调
     */
    private GMSettingConfigCallback mSettingConfigCallback = new GMSettingConfigCallback() {
        @Override
        public void configLoad() {
            SZUtil.logError("load ad 在config 回调中加载广告");
            loadAdWithCallback(mAdUnitId,scenarioId);
        }
    };

    /**
     * 展示广告
     */
    public void showBannerAd() {
        SZUtil.logError("====加载成功显示banner====");
        /**
         * 加载成功才能展示
         */
        if (bannerContainer != null) {
            if (getBannerAd() != null) {
                // 在调用getBannerView之前，可以选择使用isReady进行判断，当前是否有可用广告。
                if (!getBannerAd().isReady()) {
                    return;
                }
                //横幅广告容器的尺寸必须至少与横幅广告一样大。如果您的容器留有内边距，实际上将会减小容器大小。如果容器无法容纳横幅广告，则横幅广告不会展示
                /**
                 * mBannerViewAd.getBannerView()一个广告对象只能调用一次，第二次为null
                 */
                View view = getBannerAd().getBannerView();
                if (view != null) {
                    bannerContainer.removeAllViews();
                    bannerContainer.addView(view, getSmallUnifiedBannerLayoutParams());
                }
            }
        }
    }

    private FrameLayout.LayoutParams getSmallUnifiedBannerLayoutParams() {
        int width = SZUtil.dip2px(230);
        return new FrameLayout.LayoutParams(width, Math.round(width / 6.4F));
    }
    private FrameLayout.LayoutParams getBigUnifiedBannerLayoutParams() {
        Point screenSize = new Point();
        mActivity.getWindowManager().getDefaultDisplay().getSize(screenSize);
        return new FrameLayout.LayoutParams(screenSize.x, Math.round(screenSize.x / 6.4F));
    }
//-----------以下方法非必须 ，按需使用--------------

    //展示已经加载广告的信息
    public void printLoadAdInfo() {
        if (mBannerViewAd == null) {
            return;
        }
        /**
         * 获取已经加载的clientBidding ，多阶底价广告的相关信息
         */
        List<GMAdEcpmInfo> gmAdEcpmInfos = mBannerViewAd.getMultiBiddingEcpm();
        if (gmAdEcpmInfos != null) {
            for (GMAdEcpmInfo info : gmAdEcpmInfos) {
                SZUtil.logError("***多阶+client相关信息*** AdNetworkPlatformId" + info.getAdNetworkPlatformId()
                        + "  AdNetworkRitId:" + info.getAdNetworkRitId()
                        + "  ReqBiddingType:" + info.getReqBiddingType()
                        + "  PreEcpm:" + info.getPreEcpm()
                        + "  LevelTag:" + info.getLevelTag()
                        + "  ErrorMsg:" + info.getErrorMsg()
                        + "  request_id:" + info.getRequestId());
            }
        }

        /**
         * 获取实时填充/缓存池中价格最优的代码位信息即相关价格信息，每次只有一个信息
         */
        GMAdEcpmInfo gmAdEcpmInfo = mBannerViewAd.getBestEcpm();
        if (gmAdEcpmInfo != null) {
            SZUtil.logError("***实时填充/缓存池中价格最优的代码位信息*** AdNetworkPlatformId" + gmAdEcpmInfo.getAdNetworkPlatformId()
                    + "  AdNetworkRitId:" + gmAdEcpmInfo.getAdNetworkRitId()
                    + "  ReqBiddingType:" + gmAdEcpmInfo.getReqBiddingType()
                    + "  PreEcpm:" + gmAdEcpmInfo.getPreEcpm()
                    + "  LevelTag:" + gmAdEcpmInfo.getLevelTag()
                    + "  ErrorMsg:" + gmAdEcpmInfo.getErrorMsg()
                    + "  request_id:" + gmAdEcpmInfo.getRequestId());
        }

        /**
         * 获取获取当前缓存池的全部信息
         */
        List<GMAdEcpmInfo> gmCacheInfos = mBannerViewAd.getCacheList();
        if (gmCacheInfos != null) {
            for (GMAdEcpmInfo info : gmCacheInfos) {
                SZUtil.logError("***缓存池的全部信息*** AdNetworkPlatformId" + info.getAdNetworkPlatformId()
                        + "  AdNetworkRitId:" + info.getAdNetworkRitId()
                        + "  ReqBiddingType:" + info.getReqBiddingType()
                        + "  PreEcpm:" + info.getPreEcpm()
                        + "  LevelTag:" + info.getLevelTag()
                        + "  ErrorMsg:" + info.getErrorMsg()
                        + "  request_id:" + info.getRequestId());
            }
        }
    }

    //打印加载失败的adn错误信息
    public void printLoadFailAdnInfo() {
        if (mBannerViewAd == null) {
            return;
        }

        // 获取本次waterfall加载中，加载失败的adn错误信息。
        SZUtil.logError("InterstitialFull ad loadinfos: " + mBannerViewAd.getAdLoadInfoList());
    }

    //打印已经展示的广告信息
    public void printShowAdInfo() {
        if (mBannerViewAd == null) {
            return;
        }
        GMAdEcpmInfo gmAdEcpmInfo = mBannerViewAd.getShowEcpm();
        if (gmAdEcpmInfo == null) {
            return;
        }
        SZUtil.logError("展示的广告信息 ：adNetworkPlatformName: " + gmAdEcpmInfo.getAdNetworkPlatformName() + "   adNetworkRitId：" + gmAdEcpmInfo.getAdNetworkRitId() + "   preEcpm: " + gmAdEcpmInfo.getPreEcpm());
    }
}
